package com.wewins.fota.controller;

import com.wewins.fota.bean.bo.DownloadReq;
import com.wewins.fota.bean.dto.ResponseRst;
import com.wewins.fota.service.FotaVersionService;
import com.wewins.fota.util.FileUtil;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.validator.constraints.Range;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotBlank;
import java.io.IOException;

import static org.apache.tools.ant.launch.Locator.encodeURI;

@Slf4j
@Controller
public class VersionController {


    private final FotaVersionService fotaVersionService;

    @Autowired
    public VersionController(FotaVersionService fotaVersionService) {
        this.fotaVersionService = fotaVersionService;
    }

    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    @ResponseBody
    public ResponseRst<String> upload(@RequestParam("file") MultipartFile file, @RequestParam String product) {
        return fotaVersionService.upload(file, product);
    }

    @PostMapping("/record")
    @ResponseBody
    public ResponseRst<Integer> writeLog(@Validated @RequestBody DownloadReq req) {
        log.info("params:" + req);
        return ResponseRst.<Integer>builder()
                .data(fotaVersionService.writeLog(req))
                .build().withOk();
    }

    @GetMapping("/download/{relativePath}/{fileName:.*\\.pkg}")
    public void download(
            HttpServletRequest request,
            HttpServletResponse response,
            @PathVariable String relativePath,
            @PathVariable String fileName,
            @NotBlank @RequestParam String product,
            @NotBlank @RequestParam String imei,
            @NotBlank @RequestParam("old_version") String srcVersion,
            @NotBlank @RequestParam("new_version") String dstVersion,
            @Range(min = 0, max = 1, message = "下载类型仅支持0或1") @RequestParam int auto
    ) {
        DownloadReq downloadReq = DownloadReq.builder()
                .product(product)
                .imei(imei)
                .srcVersion(srcVersion)
                .dstVersion(dstVersion)
                .autoDownload(auto)
                .reqServer(request.getHeader("X-Real-IP"))
                .respServer(request.getHeader("Host"))
                .build();
        fotaVersionService.writeLog(downloadReq);
        try {
            response.setCharacterEncoding("utf-8");
            response.setContentType("application/octet-stream");
            String uriName = encodeURI(fileName);
            response.setHeader("Content-Disposition", "attachment;filename=\"" + uriName + "\";filename*=utf-8''" + uriName);
            FileUtil.load(response, fotaVersionService.loadFile(relativePath, fileName));
        } catch (IOException e) {
            response.setStatus(HttpStatus.BAD_REQUEST.value());
            log.error("File not exist.", e);
        } catch (Exception e) {
            response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
            log.error("unknown err.", e);
        }
    }
}
